import 'dart:io';

import 'package:flutter/material.dart';
import '../ui.dart';
import 'package:permission_handler/permission_handler.dart';
export 'package:permission_handler/permission_handler.dart';

class UiPermissionData {
  String name;
  Permission permission;
  bool isGranted = false;
  bool onlyIOS = false;
  bool onlyAndroid = false;
  UiPermissionData(
    this.name,
    this.permission, {
    this.onlyAndroid = false,
    this.onlyIOS = false,
  });
}

class UiPeromission extends StatefulWidget {
  const UiPeromission({
    super.key,
    this.title = '以下权限需要您的授权',
    this.intro,
    this.permissions = const [],
  });

  final String title;
  final String? intro;
  final List<UiPermissionData> permissions;

  static Future<bool> check(
    BuildContext context, {
    String title = '',
    String? intro,
    List<UiPermissionData> permissions = const [],
  }) async {
    var list = permissions.where((element) {
      if (Platform.isAndroid) {
        return !element.onlyIOS;
      }
      if (Platform.isIOS) {
        return !element.onlyAndroid;
      }
      return true;
    }).toList();
    if (list.isEmpty) {
      return true;
    }
    var res = await showDialog(
      context: context,
      useSafeArea: false,
      builder: (context) {
        return UiPeromission(
          title: title,
          intro: intro,
          permissions: list,
        );
      },
    );
    return res == true;
  }

  @override
  State<UiPeromission> createState() => _UiPeromissionState();
}

class _UiPeromissionState extends State<UiPeromission> {
  List<UiPermissionData> permissions = [];
  bool isClosed = false;
  @override
  void initState() {
    permissions = widget.permissions;
    checkPermission();
    super.initState();
  }

  ///检测权限
  Future<bool> checkPermission() async {
    for (var item in permissions.where((element) => !element.isGranted)) {
      PermissionStatus status = await item.permission.status;
      item.isGranted = status == PermissionStatus.granted ||
          status == PermissionStatus.limited;
    }
    setState(() {});

    if (hasFullPermission) {
      pop();
    }

    return hasFullPermission;
  }

  bool get hasFullPermission {
    return permissions.where((element) => !element.isGranted).isEmpty;
  }

  Future<void> requestPermission(UiPermissionData item) async {
    PermissionStatus status = await item.permission.request();
    if (status == PermissionStatus.permanentlyDenied) {
      await openAppSettings();
    }
    checkPermission();
  }

  pop() {
    if (Navigator.of(context).canPop() && !isClosed) {
      isClosed = true;
      Navigator.of(context).pop(hasFullPermission);
    }
  }

  @override
  Widget build(BuildContext context) {
    return UiLifeCycle(
      onResumed: () {
        checkPermission();
      },
      child: Container(
        color: Colors.black38,
        child: Center(
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 10),
            constraints: const BoxConstraints(maxWidth: 300),
            clipBehavior: Clip.hardEdge,
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: DefaultTextStyle(
              style: const TextStyle(color: Colors.black),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AspectRatio(
                    aspectRatio: 419 / 150,
                    child: Container(
                      color: Colors.grey,
                      child: Image.asset('res/images/request-permission.jpg'),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.title,
                          textScaler: const TextScaler.linear(1.15),
                        ),
                        if (widget.intro != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 5.0),
                            child: Text(
                              widget.intro ?? '',
                              style: const TextStyle(color: Colors.black54),
                            ),
                          ),
                        const SizedBox(height: 10),
                        for (var item in permissions)
                          UiTap(
                            onTap: () {
                              if (!item.isGranted) {
                                requestPermission(item);
                              }
                            },
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 10),
                              child: Row(
                                children: [
                                  Expanded(child: Text(item.name)),
                                  const SizedBox(width: 10),
                                  Text(
                                    item.isGranted ? '已授权' : '去授权',
                                    style: TextStyle(
                                      color: item.isGranted
                                          ? Colors.blue
                                          : Colors.black54,
                                    ),
                                  ),
                                  const Icon(
                                    Icons.arrow_forward_ios,
                                    size: 16,
                                    color: Colors.grey,
                                  )
                                ],
                              ),
                            ),
                          ),
                        const SizedBox(height: 15),
                        SizedBox(
                          width: double.infinity,
                          child: OutlinedButton(
                            onPressed: pop,
                            style: OutlinedButton.styleFrom(
                              splashFactory: NoSplash.splashFactory,
                              side: const BorderSide(
                                color: Colors.grey,
                                width: 0.3,
                              ),
                            ),
                            child: const Text(
                              '暂不授权',
                              style: TextStyle(color: Colors.black54),
                            ),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
